<?php

/**
 * 文件注释
 *
 * Author: Liam
 * Datetime: 03/22/18 10:45 AM
 */

namespace ApiBundle\Controller;

use BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;

class ApplyController extends BaseController
{
    /**
     * 报名
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function newApplyAction(Request $request)
    {
        $mobile = $request->get('phone');
        $name = $request->get('name');
        $age = $request->get('age');
        $created_at = date('Y-m-d h:i:s',time());
        $year = date('Y',time());

        $new_apply = array(
            'name' => $name,
            'age' => $age,
            'mobile' => $mobile,
            'created_at' => $created_at,
            'year' => $year
        );

        $conn = $this->get('database_connection');

        $id = $conn->fetchColumn("SELECT id FROM apply WHERE mobile = ?", array($mobile));

        if ($id) {
            return $this->jsonResponse('该手机号已经报名成功，请勿重复报名', 1);
        }

        $result = $conn->insert("apply", $new_apply);
        if($result){
            return $this->jsonResponse('报名成功', 0);
        }
    }

    /**
     * 改变联系状态
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */

    public function applyStatusAction(Request $request)
    {
        $id = $request->get('id');
        $status = $request->get('status');
        $message = $request->get('mes');

        if ($message == '') {
            return $this->jsonResponse('备注信息为空', 1);
        }

        $conn = $this->get('database_connection');
        $data = $conn->fetchAssoc("SELECT * FROM apply WHERE id = '". $id ."'");
        $data['status'] = $status;
        $data['message'] = $message;

        $conn->update('apply', $data, array('id'=> $id));

        return $this->jsonResponse('操作成功', 0);
    }

    /**
     * 删除
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */

    public function applyDelAction(Request $request)
    {
        $id = $request->get('id');

        if ($id == null) {
            return $this->jsonResponse('缺少参数', 1);
        }
        $this->get('database_connection')->delete('apply', array('id' => $id));

        return $this->jsonResponse('操作成功', 0);
    }
}